import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/router';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import { PrismLight as SyntaxHighlighter } from 'react-syntax-highlighter';
import { oneLight, oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
// 添加常用语言支持
import jsx from 'react-syntax-highlighter/dist/cjs/languages/prism/jsx';
import javascript from 'react-syntax-highlighter/dist/cjs/languages/prism/javascript';
import typescript from 'react-syntax-highlighter/dist/cjs/languages/prism/typescript';
import css from 'react-syntax-highlighter/dist/cjs/languages/prism/css';
import html from 'react-syntax-highlighter/dist/cjs/languages/prism/markup';
import json from 'react-syntax-highlighter/dist/cjs/languages/prism/json';
import markdown from 'react-syntax-highlighter/dist/cjs/languages/prism/markdown';
import bash from 'react-syntax-highlighter/dist/cjs/languages/prism/bash';
import python from 'react-syntax-highlighter/dist/cjs/languages/prism/python';
import java from 'react-syntax-highlighter/dist/cjs/languages/prism/java';
import sql from 'react-syntax-highlighter/dist/cjs/languages/prism/sql';
import Layout from '../../components/Layout';
import SEO from '../../components/SEO';
import { useSession } from 'next-auth/react';
import MdEditor from 'react-markdown-editor-lite';
import { useTheme } from 'next-themes';
import 'react-markdown-editor-lite/lib/index.css';

// 注册语言
SyntaxHighlighter.registerLanguage('jsx', jsx);
SyntaxHighlighter.registerLanguage('javascript', javascript);
SyntaxHighlighter.registerLanguage('js', javascript);
SyntaxHighlighter.registerLanguage('typescript', typescript);
SyntaxHighlighter.registerLanguage('ts', typescript);
SyntaxHighlighter.registerLanguage('css', css);
SyntaxHighlighter.registerLanguage('html', html);
SyntaxHighlighter.registerLanguage('json', json);
SyntaxHighlighter.registerLanguage('markdown', markdown);
SyntaxHighlighter.registerLanguage('md', markdown);
SyntaxHighlighter.registerLanguage('bash', bash);
SyntaxHighlighter.registerLanguage('shell', bash);
SyntaxHighlighter.registerLanguage('sh', bash);
SyntaxHighlighter.registerLanguage('python', python);
SyntaxHighlighter.registerLanguage('py', python);
SyntaxHighlighter.registerLanguage('java', java);
SyntaxHighlighter.registerLanguage('sql', sql);

// 解析 Markdown 内容获取标题
const parseHeadings = (content) => {
  const headingRegex = /^(#{1,6})\s+([^\n]+)$/gm;
  const headings = [];
  let match;
  const idCount = new Map();

  const contentWithoutCodeBlocks = content.replace(/```[\s\S]*?```/g, '');

  while ((match = headingRegex.exec(contentWithoutCodeBlocks)) !== null) {
    const level = match[1].length;
    const text = match[2].trim();
    
    if (!text || /^[#*_`\s-]+$/.test(text)) continue;
    
    let id = text
      .toLowerCase()
      .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
      .replace(/^-+|-+$/g, '');
    
    const count = idCount.get(id) || 0;
    if (count > 0) {
      id = `${id}-${count + 1}`;
    }
    idCount.set(id, count + 1);
    
    headings.push({ level, text, id });
  }

  return headings;
};

// 生成标题 ID 的辅助函数
const generateHeadingId = (text, level) => {
  if (!text) return '';
  
  if (/^[#*_`\s-]+$/.test(text)) return '';
  
  let id = text
    .toString()
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
    .replace(/^-+|-+$/g, '');
  
  // 移除 section- 前缀，统一 ID 格式
  if (id.startsWith('section-')) {
    id = id.replace('section-', '');
  }
  
  console.log(`生成标题ID: 级别=${level}, 文本=${text}, ID=${id}`);
  return id;
};

// 添加复制功能的辅助函数
const copyToClipboard = async (text) => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      // 对于 HTTPS 环境，使用 Clipboard API
      await navigator.clipboard.writeText(text);
    } else {
      // 回退方案：使用传统的复制方法
      const textArea = document.createElement('textarea');
      textArea.value = text;
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        document.execCommand('copy');
      } catch (err) {
        console.error('复制失败:', err);
        throw new Error('复制失败');
      }
      textArea.remove();
    }
    return true;
  } catch (err) {
    console.error('复制失败:', err);
    return false;
  }
};

// 代码复制按钮组件
const CopyButton = ({ code }) => {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      const success = await copyToClipboard(code);
      if (success) {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      } else {
        alert('复制失败，请手动复制');
      }
    } catch (err) {
      console.error('Failed to copy:', err);
      alert('复制失败，请手动复制');
    }
  };

  return (
    <div className="relative">
      <button
        onClick={handleCopy}
        className="p-1 text-gray-500 dark:text-gray-300 hover:text-gray-700 dark:hover:text-gray-100 rounded hover:bg-gray-100 dark:hover:bg-[rgb(44,47,54)] transition-colors"
        title={copied ? "复制成功！" : "复制代码"}
      >
        {!copied ? (
          <svg
            className="w-4 h-4 sm:w-5 sm:h-5"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"
            />
          </svg>
        ) : (
          <svg 
            className="w-4 h-4 sm:w-5 sm:h-5 text-green-500 dark:text-green-400"
            fill="none" 
            stroke="currentColor" 
            viewBox="0 0 24 24"
          >
            <path 
              strokeLinecap="round" 
              strokeLinejoin="round" 
              strokeWidth={2} 
              d="M5 13l4 4L19 7" 
            />
          </svg>
        )}
      </button>
      {copied && (
        <div className="absolute right-full mr-2 top-0 bg-green-600 dark:bg-green-500 text-white text-xs px-2 py-1 rounded shadow-md whitespace-nowrap z-50">
          复制成功！
        </div>
      )}
    </div>
  );
};

export default function DocPage() {
  const router = useRouter();
  const { slug } = router.query;
  const [content, setContent] = useState('');
  const [headings, setHeadings] = useState([]);
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const { data: session } = useSession();
  const [isEditing, setIsEditing] = useState(false);
  const [editorError, setEditorError] = useState(null);
  const { theme } = useTheme();
  const isDarkMode = theme === 'dark';
  const [copied, setCopied] = useState(false);
  const editorDebounceRef = useRef(null);
  const [previewContent, setPreviewContent] = useState('');

  // 用于SEO的标题和摘要
  const [docTitle, setDocTitle] = useState('');
  const [docDescription, setDocDescription] = useState('');
  const [docKeywords, setDocKeywords] = useState('');

  // 添加处理 URL 锚点链接的 useEffect
  useEffect(() => {
    if (content && !isLoading) {
      // 获取 URL 中的 hash 部分（去掉 # 符号）
      const hash = window.location.hash.slice(1);
      if (hash) {
        // 等待内容渲染完成后再滚动
        const timer = setTimeout(() => {
          console.log(`检测到 URL 锚点链接: ${hash}`);
          // 移除 section- 前缀（如果有）
          const cleanHash = hash.replace('section-', '');
          scrollToHeading(cleanHash);
        }, 1500); // 增加延迟时间，确保内容完全渲染

        return () => clearTimeout(timer); // 清理定时器
      }
    }
  }, [content, isLoading]);

  // 添加监听 hash 变化的处理
  useEffect(() => {
    const handleHashChange = () => {
      const hash = window.location.hash.slice(1);
      if (hash) {
        console.log(`URL hash 变化: ${hash}`);
        // 移除 section- 前缀（如果有）
        const cleanHash = hash.replace('section-', '');
        // 使用 setTimeout 确保 DOM 已更新
        setTimeout(() => {
          scrollToHeading(cleanHash);
        }, 100);
      }
    };

    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  // 滚动到指定标题的函数
  const scrollToHeading = (id) => {
    console.log(`尝试滚动到标题: ${id}`);
    
    // 尝试直接查找 ID
    let element = document.getElementById(id);
    
    // 如果找不到，尝试查找带有 section- 前缀的 ID
    if (!element) {
      element = document.getElementById(`section-${id}`);
    }
    
    if (element) {
      // 使用 scrollIntoView 并考虑固定导航栏的偏移
      const headerOffset = 80; // 导航栏高度 + 一些额外空间
      const elementPosition = element.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

      // 先滚动到目标位置
      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
      });

      // 更新 URL，但不触发页面跳转
      window.history.pushState({}, '', `#${id}`);
      
      console.log(`成功滚动到标题: ${id}`);
    } else {
      console.error(`找不到ID为 ${id} 的元素`);
      // 尝试查找所有标题元素
      const allHeadings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
      console.log('当前页面所有标题:', Array.from(allHeadings).map(h => ({ 
        id: h.id, 
        text: h.textContent,
        level: parseInt(h.tagName[1])
      })));
    }
  };

  useEffect(() => {
    if (slug) {
      setIsLoading(true);
      const filePath = slug.join('/');
      fetch(`/api/docs?filePath=${encodeURIComponent(filePath)}`)
        .then(res => res.json())
        .then(data => {
          if (data.error) {
            setError(data.error);
          } else {
            setContent(data.content);
            setHeadings(parseHeadings(data.content));
          }
        })
        .catch(err => {
          console.error('Error fetching content:', err);
          setError('加载内容失败');
        })
        .finally(() => {
          setIsLoading(false);
        });
    }
  }, [slug]);

  useEffect(() => {
    if (content) {
      const parsedHeadings = parseHeadings(content);
      setHeadings(parsedHeadings);
      
      // 提取文档标题 (第一个h1标题)
      const firstH1 = parsedHeadings.find(h => h.level === 1);
      const title = firstH1 ? firstH1.text : (slug ? slug[0] : '文档');
      setDocTitle(title);
      
      // 提取文档摘要
      const plainText = content.replace(/[#*_`]/g, '').substring(0, 500);
      const summary = plainText.split('\n').filter(line => line.trim() !== '').slice(0, 3).join(' ');
      setDocDescription(summary || `${title} - 小铭Ai梦想家智能量化交易平台文档`);
      
      // 提取关键词
      const words = plainText.split(/\s+/).filter(word => word.length > 3);
      const uniqueWords = [...new Set(words)].slice(0, 10).join(',');
      setDocKeywords(uniqueWords || `${title},量化交易,AI投资,Markdown编辑器,金融分析`);
    }
  }, [content, slug]);

  const handleEditorChange = ({ text, html }) => {
    // 直接更新编辑器内容，不触发重新渲染
    setContent(text);
    
    // 清除之前的防抖计时器
    if (editorDebounceRef.current) {
      clearTimeout(editorDebounceRef.current);
    }
    
    // 设置新的防抖计时器，延迟更新预览内容
    editorDebounceRef.current = setTimeout(() => {
      setPreviewContent(text);
      // 仅在防抖后记录日志，减少控制台输出
      console.log('Editor content updated after debounce');
    }, 500); // 500毫秒的防抖延迟
  };

  const handleSave = async () => {
    try {
      if (!content) {
        setError('内容不能为空');
        return;
      }

      if (!session?.user?.isAdmin) {
        console.log('Current session:', session);
        setError('需要管理员权限');
        return;
      }
      
      console.log('Saving content:', content);
      const filePath = slug.join('/');
      const response = await fetch('/api/docs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify({ 
          filePath,
          content 
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '保存失败');
      }

      setIsEditing(false);
      // 重新加载内容以确保同步
      const res = await fetch(`/api/docs?filePath=${encodeURIComponent(filePath)}`);
      const data = await res.json();
      if (data.error) {
        setError(data.error);
      } else {
        setContent(data.content);
        setHeadings(parseHeadings(data.content));
      }
    } catch (error) {
      console.error('Error saving content:', error);
      setError(error.message);
    }
  };

  if (error) {
    return (
      <Layout documentMenu={headings}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="bg-red-50 dark:bg-red-900 p-4 rounded-lg">
            <p className="text-red-600 dark:text-red-200">{error}</p>
          </div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout documentMenu={headings}>
      <SEO 
        title={`${docTitle} - 小铭Ai梦想家`}
        description={docDescription}
        keywords={docKeywords}
        url={`/docs/${slug ? slug.join('/') : ''}`}
        ogType="article"
      />
      <div className="flex max-w-7xl mx-auto relative">
        {/* 左侧菜单 */}
        <div className={`w-64 fixed top-0 bottom-0 bg-gray-100 dark:bg-[rgb(24,27,33)] overflow-hidden border-r border-gray-200 dark:border-[rgb(28,31,38)] transition-transform duration-300 ease-in-out z-30 ${
          isSidebarOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0'
        }`}>
          {/* 顶部空间补偿，与导航栏等高 */}
          <div className="h-16 bg-gray-100 dark:bg-[rgb(24,27,33)]" />
          
          {/* 可滚动的内容区域 */}
          <div className="absolute inset-0 top-16 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-400 dark:scrollbar-thumb-gray-500 scrollbar-track-transparent hover:scrollbar-thumb-gray-500 dark:hover:scrollbar-thumb-gray-400 scrollbar-thumb-rounded-full">
            {/* 标题和管理按钮 */}
            <div className="sticky top-0 z-10 bg-gray-100 dark:bg-[rgb(24,27,33)]">
              <div className="p-4 pb-2">
                <h2 className="text-lg font-semibold dark:text-gray-100">目录</h2>
                {session?.user?.isAdmin && (
                  <div className="flex space-x-2 mt-2">
                    <button
                      onClick={() => setIsEditing(!isEditing)}
                      className="bg-gray-200 dark:bg-[rgb(28,31,38)] text-gray-700 dark:text-gray-300 px-4 py-1.5 text-sm hover:bg-gray-300 dark:hover:bg-[rgb(38,41,48)] transition-colors flex-1 shadow-none"
                      style={{ borderRadius: 0 }}
                    >
                      {isEditing ? '预览' : '编辑'}
                    </button>
                    {isEditing && (
                      <button
                        onClick={handleSave}
                        className="bg-gray-200 dark:bg-[rgb(28,31,38)] text-gray-700 dark:text-gray-300 px-4 py-1.5 text-sm hover:bg-gray-300 dark:hover:bg-[rgb(38,41,48)] transition-colors flex-1 shadow-none"
                        style={{ borderRadius: 0 }}
                      >
                        保存
                      </button>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* 菜单列表 */}
            <div className="flex flex-col" style={{ isolation: 'isolate' }}>
              {headings.reduce((groups, heading, index) => {
                const isFirstLevel = heading.level === 1;
                
                if (isFirstLevel) {
                  const subHeadings = [];
                  let i = index + 1;
                  while (i < headings.length && headings[i].level > 1) {
                    subHeadings.push(headings[i]);
                    i++;
                  }
                  
                  groups.push(
                    <div key={heading.id} className="menu-group" style={{ position: 'relative' }}>
                      <a
                        href={`#${heading.id}`}
                        onClick={(e) => {
                          e.preventDefault();
                          scrollToHeading(heading.id);
                          if (window.innerWidth < 1024) {
                            setIsSidebarOpen(false);
                          }
                        }}
                        className="!block text-left text-sm hover:text-blue-600 dark:text-gray-200 font-semibold bg-gray-100 dark:bg-[rgb(24,27,33)] py-2 px-4 hover:bg-gray-200 dark:hover:bg-[rgb(38,41,48)] transition-colors"
                        style={{ 
                          paddingLeft: '1rem',
                          borderRadius: '0 !important',
                          boxShadow: 'none !important',
                          position: 'relative',
                          zIndex: 2,
                          transform: 'translate3d(0,0,0)'
                        }}
                      >
                        {heading.text}
                      </a>
                      {subHeadings.length > 0 && (
                        <div 
                          className="sub-menu !bg-gray-100 dark:!bg-[rgb(24,27,33)]" 
                          style={{ 
                            borderRadius: '0 !important',
                            margin: '0 !important',
                            padding: '0 !important',
                            boxShadow: 'none !important',
                            position: 'relative',
                            zIndex: 1,
                            marginTop: '-8px !important',
                            transform: 'translate3d(0,0,0)'
                          }}
                        >
                          {subHeadings.map((subHeading) => (
                            <a
                              key={subHeading.id}
                              href={`#${subHeading.id}`}
                              onClick={(e) => {
                                e.preventDefault();
                                scrollToHeading(subHeading.id);
                                if (window.innerWidth < 1024) {
                                  setIsSidebarOpen(false);
                                }
                              }}
                              className="!block text-left text-sm hover:text-blue-600 dark:text-gray-300 dark:hover:text-blue-400 py-1.5 px-2 hover:bg-gray-200 dark:hover:bg-[rgb(38,41,48)] transition-colors"
                              style={{ 
                                paddingLeft: `${(subHeading.level - 1) * 1.25 + 0.5}rem`,
                                fontSize: `${1 - (subHeading.level - 1) * 0.05}rem`,
                                borderRadius: '0 !important',
                                marginTop: '-1px !important',
                                boxShadow: 'none !important',
                                position: 'relative',
                                backgroundColor: isDarkMode ? 'rgb(24,27,33)' : 'rgb(243,244,246)',
                                transform: 'translate3d(0,0,0)'
                              }}
                            >
                              {subHeading.text}
                            </a>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                }
                return groups;
              }, [])}
            </div>
          </div>
        </div>

        {/* 主要内容区域 */}
        <div className="flex-1 p-4 lg:ml-64 overflow-hidden bg-gray-50 dark:bg-[rgb(28,31,38)]">
          <div className="max-w-[calc(100vw-2rem)] lg:max-w-[calc(100vw-18rem)] mx-auto overflow-hidden rounded-lg">
            {error && (
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span className="block sm:inline">{error}</span>
              </div>
            )}

            {editorError && (
              <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span className="block sm:inline">编辑器错误: {editorError}</span>
              </div>
            )}

            {isLoading ? (
              <div className="flex justify-center items-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
              </div>
            ) : isEditing ? (
              <div className="markdown-editor bg-white dark:bg-[rgb(24,27,33)] rounded-lg">
                <MdEditor
                  value={content}
                  onChange={handleEditorChange}
                  config={{
                    view: {
                      menu: true,
                      md: true,
                      html: true
                    },
                    canView: {
                      menu: true,
                      md: true,
                      html: true,
                      fullScreen: true
                    },
                    // 修复性能优化配置
                    syncScrollMode: ['limitUnilateral', 'normal', 'rightFollowLeft'][0],
                    editor: {
                      class: 'optimized-markdown-editor',  // 使用编辑器类样式
                      min: 500
                    },
                    view: {
                      menu: true,
                      md: true,
                      html: true,
                      html_class: 'optimized-html-preview'  // 使用HTML预览类样式
                    },
                    table: {
                      maxRow: 20,  // 限制表格的最大行数
                      maxCol: 10   // 限制表格的最大列数
                    },
                    allowPasteImage: true,  // 允许粘贴图片
                    imageAccept: '.jpg,.jpeg,.png,.gif',  // 接受的图片类型
                    imageResizeMode: 'none'  // 图片缩放模式
                  }}
                  renderHTML={(text) => {
                    try {
                      // 使用防抖后的预览内容而不是直接使用text
                      const contentToRender = previewContent || text;
                      return (
                        <div className="prose max-w-none dark:prose-invert">
                          <ReactMarkdown 
                            remarkPlugins={[remarkGfm]}
                            rehypePlugins={[rehypeRaw]}
                            components={{
                              h1: ({ children }) => {
                                const text = children?.toString()?.trim();
                                if (!text) return null;
                                const id = generateHeadingId(text, 1);
                                return <h1 id={id} className="scroll-mt-20">{children}</h1>;
                              },
                              h2: ({ children }) => {
                                const text = children?.toString()?.trim();
                                if (!text) return null;
                                const id = generateHeadingId(text, 2);
                                return <h2 id={id} className="scroll-mt-20">{children}</h2>;
                              },
                              h3: ({ children }) => {
                                const text = children?.toString()?.trim();
                                if (!text) return null;
                                const id = generateHeadingId(text, 3);
                                return <h3 id={id} className="scroll-mt-20">{children}</h3>;
                              },
                              h4: ({ children }) => {
                                const text = children?.toString()?.trim();
                                if (!text) return null;
                                const id = generateHeadingId(text, 4);
                                return <h4 id={id} className="scroll-mt-20">{children}</h4>;
                              },
                              h5: ({ children }) => {
                                const text = children?.toString()?.trim();
                                if (!text) return null;
                                const id = generateHeadingId(text, 5);
                                return <h5 id={id} className="scroll-mt-20">{children}</h5>;
                              },
                              h6: ({ children }) => {
                                const text = children?.toString()?.trim();
                                if (!text) return null;
                                const id = generateHeadingId(text, 6);
                                return <h6 id={id} className="scroll-mt-20">{children}</h6>;
                              },
                              table: ({ children }) => (
                                <div className="my-6 w-full">
                                  <div className="overflow-x-auto">
                                    <div className="inline-block min-w-full align-middle">
                                      <table className="w-full divide-y divide-gray-200 dark:divide-[rgb(58,61,68)] border border-gray-200 dark:border-[rgb(58,61,68)] shadow-md text-sm sm:text-base table-fixed">
                                        {children}
                                      </table>
                                    </div>
                                  </div>
                                </div>
                              ),
                              thead: ({ children }) => (
                                <thead className="bg-gray-50 dark:bg-[rgb(34,37,44)]">
                                  {children}
                                </thead>
                              ),
                              tbody: ({ children }) => (
                                <tbody className="bg-white dark:bg-[rgb(38,41,48)] divide-y divide-gray-200 dark:divide-[rgb(58,61,68)]">
                                  {children}
                                </tbody>
                              ),
                              tr: ({ children }) => (
                                <tr className="hover:bg-gray-50 dark:hover:bg-[rgb(44,47,54)] transition-colors">
                                  {children}
                                </tr>
                              ),
                              th: ({ children }) => (
                                <th className="px-3 sm:px-4 py-2 sm:py-3 text-left text-sm sm:text-base font-medium text-gray-500 dark:text-gray-200 uppercase tracking-wider border-b border-gray-200 dark:border-[rgb(58,61,68)] break-words max-w-xs truncate">
                                  {children}
                                </th>
                              ),
                              td: ({ children }) => (
                                <td className="px-3 sm:px-4 py-2 sm:py-3 text-sm sm:text-base text-gray-500 dark:text-gray-300 border-b border-gray-200 dark:border-[rgb(58,61,68)] break-words max-w-xs overflow-hidden">
                                  <div className="line-clamp-3 hover:line-clamp-none transition-all duration-200">
                                    {children}
                                  </div>
                                </td>
                              ),
                              code({ node, inline, className, children, ...props }) {
                                const match = /language-(\w+)/.exec(className || '');
                                const language = match ? match[1] : '';
                                const code = String(children).replace(/\n$/, '');

                                if (!inline && match) {
                                  return (
                                    <div className="relative group w-full">
                                      <div className="absolute right-2 top-2 flex items-center space-x-2 z-10">
                                        <span className="text-xs sm:text-sm text-gray-500 dark:text-gray-300">
                                          {language}
                                        </span>
                                        <CopyButton code={code} />
                                      </div>
                                      <div className="overflow-x-auto">
                                        <SyntaxHighlighter
                                          style={isDarkMode ? oneDark : oneLight}
                                          language={language}
                                          PreTag="div"
                                          wrapLines={true}
                                          wrapLongLines={true}
                                          codeTagProps={{
                                            style: {
                                              display: 'block',
                                              paddingLeft: '0',
                                            }
                                          }}
                                          customStyle={{
                                            margin: 0,
                                            borderRadius: '0.5rem',
                                            padding: '1.25rem',
                                            backgroundColor: isDarkMode ? 'rgb(38,41,48)' : '#fafafa',
                                            border: isDarkMode ? '1px solid rgb(58,61,68)' : '1px solid #f0f0f0',
                                            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
                                            fontSize: '0.875rem',
                                            lineHeight: '1.5',
                                            width: '100%',
                                            maxWidth: '100%',
                                            WebkitTextSizeAdjust: '100%',
                                            MozTextSizeAdjust: '100%',
                                            msTextSizeAdjust: '100%',
                                            textSizeAdjust: '100%',
                                          }}
                                          {...props}
                                        >
                                          {code}
                                        </SyntaxHighlighter>
                                      </div>
                                    </div>
                                  );
                                }

                                return (
                                  <code
                                    className="bg-gray-50 dark:bg-[rgb(38,41,48)] rounded px-2 py-1 text-base sm:text-lg text-gray-700 dark:text-gray-300 border border-gray-100 dark:border-[rgb(58,61,68)] whitespace-normal break-words"
                                    style={{
                                      WebkitTextSizeAdjust: '100%',
                                      MozTextSizeAdjust: '100%',
                                      msTextSizeAdjust: '100%',
                                      textSizeAdjust: '100%',
                                    }}
                                    {...props}
                                  >
                                    {children}
                                  </code>
                                );
                              },
                              div: ({ children, ...props }) => {
                                const align = props.align || 'left';
                                return (
                                  <div className={`text-${align}`} {...props}>
                                    {children}
                                  </div>
                                );
                              },
                              img: ({ src, alt, ...props }) => (
                                <img
                                  src={src}
                                  alt={alt}
                                  className="inline-block mx-1"
                                  {...props}
                                />
                              ),
                              a: ({ href, children, ...props }) => (
                                <a
                                  href={href}
                                  {...props}
                                >
                                  {children}
                                </a>
                              ),
                              blockquote: ({ children }) => (
                                <blockquote>
                                  {children}
                                </blockquote>
                              ),
                              font: ({ color, children, ...props }) => {
                                // 创建样式对象
                                const style = color ? { color } : {};
                                
                                // 确保父组件能正确渲染子组件
                                return (
                                  <span style={style} {...props}>
                                    {children}
                                  </span>
                                );
                              },
                              ul: ({ children }) => (
                                <ul className="list-disc space-y-2 my-4">
                                  {children}
                                </ul>
                              ),
                              ol: ({ children }) => (
                                <ol className="list-decimal space-y-2 my-4">
                                  {children}
                                </ol>
                              ),
                              li: ({ children }) => (
                                <li className="text-gray-700 dark:text-gray-300">
                                  {children}
                                </li>
                              ),
                            }}
                          >
                            {contentToRender}
                          </ReactMarkdown>
                        </div>
                      );
                    } catch (error) {
                      console.error('Error rendering markdown:', error);
                      return <div>渲染错误</div>;
                    }
                  }}
                  onSave={handleSave}
                />
              </div>
            ) : (
              <div className="prose max-w-none relative dark:prose-invert overflow-hidden
                prose-headings:dark:text-gray-100 
                prose-p:dark:text-gray-200 
                prose-a:dark:text-blue-400 
                prose-strong:dark:text-gray-100 
                prose-code:dark:text-gray-200 
                prose-code:dark:bg-[rgb(38,41,48)] 
                prose-pre:dark:bg-[rgb(38,41,48)] 
                prose-thead:dark:bg-[rgb(34,37,44)] 
                prose-tr:dark:border-[rgb(58,61,68)] 
                prose-td:dark:border-[rgb(58,61,68)] 
                prose-th:dark:border-[rgb(58,61,68)]
                sm:prose-base
                prose-p:text-base sm:prose-p:text-lg
                prose-headings:mb-6
                prose-h1:text-2xl sm:prose-h1:text-3xl
                prose-h2:text-xl sm:prose-h2:text-2xl
                prose-h3:text-lg sm:prose-h3:text-xl
                prose-h4:text-base sm:prose-h4:text-lg
                prose-li:text-base sm:prose-li:text-lg
                prose-code:text-sm sm:prose-code:text-base
                prose-pre:text-sm sm:prose-pre:text-base
                prose-p:leading-[1.95rem]
                prose-li:leading-[1.825rem]
                prose-p:mb-6
                prose-ul:mb-6">
                <ReactMarkdown
                  remarkPlugins={[remarkGfm]}
                  rehypePlugins={[rehypeRaw]}
                  components={{
                    h1: ({ children }) => {
                      const text = children?.toString()?.trim();
                      if (!text) return null;
                      const id = generateHeadingId(text, 1);
                      return <h1 id={id} className="scroll-mt-20">{children}</h1>;
                    },
                    h2: ({ children }) => {
                      const text = children?.toString()?.trim();
                      if (!text) return null;
                      const id = generateHeadingId(text, 2);
                      return <h2 id={id} className="scroll-mt-20">{children}</h2>;
                    },
                    h3: ({ children }) => {
                      const text = children?.toString()?.trim();
                      if (!text) return null;
                      const id = generateHeadingId(text, 3);
                      return <h3 id={id} className="scroll-mt-20">{children}</h3>;
                    },
                    h4: ({ children }) => {
                      const text = children?.toString()?.trim();
                      if (!text) return null;
                      const id = generateHeadingId(text, 4);
                      return <h4 id={id} className="scroll-mt-20">{children}</h4>;
                    },
                    h5: ({ children }) => {
                      const text = children?.toString()?.trim();
                      if (!text) return null;
                      const id = generateHeadingId(text, 5);
                      return <h5 id={id} className="scroll-mt-20">{children}</h5>;
                    },
                    h6: ({ children }) => {
                      const text = children?.toString()?.trim();
                      if (!text) return null;
                      const id = generateHeadingId(text, 6);
                      return <h6 id={id} className="scroll-mt-20">{children}</h6>;
                    },
                    table: ({ children }) => (
                      <div className="my-6 w-full">
                        <div className="overflow-x-auto">
                          <div className="inline-block min-w-full align-middle">
                            <table className="w-full divide-y divide-gray-200 dark:divide-[rgb(58,61,68)] border border-gray-200 dark:border-[rgb(58,61,68)] shadow-md text-sm sm:text-base table-fixed">
                              {children}
                            </table>
                          </div>
                        </div>
                      </div>
                    ),
                    thead: ({ children }) => (
                      <thead className="bg-gray-50 dark:bg-[rgb(34,37,44)]">
                        {children}
                      </thead>
                    ),
                    tbody: ({ children }) => (
                      <tbody className="bg-white dark:bg-[rgb(38,41,48)] divide-y divide-gray-200 dark:divide-[rgb(58,61,68)]">
                        {children}
                      </tbody>
                    ),
                    tr: ({ children }) => (
                      <tr className="hover:bg-gray-50 dark:hover:bg-[rgb(44,47,54)] transition-colors">
                        {children}
                      </tr>
                    ),
                    th: ({ children }) => (
                      <th className="px-3 sm:px-4 py-2 sm:py-3 text-left text-sm sm:text-base font-medium text-gray-500 dark:text-gray-200 uppercase tracking-wider border-b border-gray-200 dark:border-[rgb(58,61,68)] break-words max-w-xs truncate">
                        {children}
                      </th>
                    ),
                    td: ({ children }) => (
                      <td className="px-3 sm:px-4 py-2 sm:py-3 text-sm sm:text-base text-gray-500 dark:text-gray-300 border-b border-gray-200 dark:border-[rgb(58,61,68)] break-words max-w-xs overflow-hidden">
                        <div className="line-clamp-3 hover:line-clamp-none transition-all duration-200">
                          {children}
                        </div>
                      </td>
                    ),
                    code({ node, inline, className, children, ...props }) {
                      const match = /language-(\w+)/.exec(className || '');
                      const language = match ? match[1] : '';
                      const code = String(children).replace(/\n$/, '');

                      if (!inline && match) {
                        return (
                          <div className="relative group w-full">
                            <div className="absolute right-2 top-2 flex items-center space-x-2 z-10">
                              <span className="text-xs sm:text-sm text-gray-500 dark:text-gray-300">
                                {language}
                              </span>
                              <CopyButton code={code} />
                            </div>
                            <div className="overflow-x-auto">
                              <SyntaxHighlighter
                                style={isDarkMode ? oneDark : oneLight}
                                language={language}
                                PreTag="div"
                                wrapLines={true}
                                wrapLongLines={true}
                                codeTagProps={{
                                  style: {
                                    display: 'block',
                                    paddingLeft: '0',
                                  }
                                }}
                                customStyle={{
                                  margin: 0,
                                  borderRadius: '0.5rem',
                                  padding: '1.25rem',
                                  backgroundColor: isDarkMode ? 'rgb(38,41,48)' : '#fafafa',
                                  border: isDarkMode ? '1px solid rgb(58,61,68)' : '1px solid #f0f0f0',
                                  boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
                                  fontSize: '0.875rem',
                                  lineHeight: '1.5',
                                  width: '100%',
                                  maxWidth: '100%',
                                  WebkitTextSizeAdjust: '100%',
                                  MozTextSizeAdjust: '100%',
                                  msTextSizeAdjust: '100%',
                                  textSizeAdjust: '100%',
                                }}
                                {...props}
                              >
                                {code}
                              </SyntaxHighlighter>
                            </div>
                          </div>
                        );
                      }

                      return (
                        <code
                          className="bg-gray-50 dark:bg-[rgb(38,41,48)] rounded px-2 py-1 text-base sm:text-lg text-gray-700 dark:text-gray-300 border border-gray-100 dark:border-[rgb(58,61,68)] whitespace-normal break-words"
                          style={{
                            WebkitTextSizeAdjust: '100%',
                            MozTextSizeAdjust: '100%',
                            msTextSizeAdjust: '100%',
                            textSizeAdjust: '100%',
                          }}
                          {...props}
                        >
                          {children}
                        </code>
                      );
                    },
                    div: ({ children, ...props }) => {
                      const align = props.align || 'left';
                      return (
                        <div className={`text-${align}`} {...props}>
                          {children}
                        </div>
                      );
                    },
                    img: ({ src, alt, ...props }) => (
                      <img
                        src={src}
                        alt={alt}
                        className="inline-block mx-1"
                        {...props}
                      />
                    ),
                    a: ({ href, children, ...props }) => (
                      <a
                        href={href}
                        {...props}
                      >
                        {children}
                      </a>
                    ),
                    blockquote: ({ children }) => (
                      <blockquote>
                        {children}
                      </blockquote>
                    ),
                    font: ({ color, children, ...props }) => {
                      // 创建样式对象
                      const style = color ? { color } : {};
                      
                      // 确保父组件能正确渲染子组件
                      return (
                        <span style={style} {...props}>
                          {children}
                        </span>
                      );
                    },
                    ul: ({ children }) => (
                      <ul className="list-disc space-y-2 my-4">
                        {children}
                      </ul>
                    ),
                    ol: ({ children }) => (
                      <ol className="list-decimal space-y-2 my-4">
                        {children}
                      </ol>
                    ),
                    li: ({ children }) => (
                      <li className="text-gray-700 dark:text-gray-300">
                        {children}
                      </li>
                    ),
                  }}
                >
                  {content}
                </ReactMarkdown>
              </div>
            )}
          </div>
        </div>
      </div>
    </Layout>
  );
} 